package cn.rkylin.oms.warehouseDocking.adapter;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.resend.domain.AfterSaleResend;
import cn.rkylin.oms.resend.service.IAfterSaleResendService;
import cn.rkylin.oms.sysOrder.domain.SysOrderGoods;
import cn.rkylin.oms.sysOrder.service.SysOrderServiceImpl;
import cn.rkylin.oms.sysOrder.vo.SysOrderVO;
import cn.rkylin.oms.sysreturn.service.ISysReturnService;
import cn.rkylin.oms.sysreturn.vo.SysReturnVO;
import cn.rkylin.oms.system.project.service.IProjectManagerService;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.warehouse.returnStockin.service.ReturnStockinServiceImpl;
import cn.rkylin.oms.warehouse.returnStockin.vo.ReturnStockinVO;
import cn.rkylin.oms.warehouse.shiporder.domain.ShiporderSku;
import cn.rkylin.oms.warehouse.shiporder.service.ShiporderServiceImpl;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO;
import cn.rkylin.oms.warehouseDocking.domain.*;
import cn.rkylin.oms.warehouseDocking.service.*;
import cn.rkylin.oms.warehouseDocking.service.qimen.*;
import cn.rkylin.oms.warehouseDocking.vo.StockVO;
import cn.rkylin.oms.warehouseDocking.vo.qimen.*;
import com.alibaba.fastjson.JSON;
import com.qimen.api.DefaultQimenClient;
import com.qimen.api.QimenClient;
import com.qimen.api.request.*;
import com.qimen.api.request.InventoryQueryRequest.Criteria;
import com.qimen.api.response.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 淘宝奇门仓库访问者
 *
 * @author jipengcheng
 * @created 2017年10月16日
 */
@Component("qimenVisitor")
public class QimenVisitor extends WarehouseDockingVisitor {

    private static final Log logger = LogFactory.getLog(QimenVisitor.class);
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private LogUtil logUtil;

    @Autowired
    StorService storService;

    @Autowired
    GoodsSynchronizeService goodsSynchronizeService;

    @Autowired
    OtherStockoutCreateService otherStockoutCreateService;

    @Autowired
    ShipOrderCreateService shipOrderCreateService;

    @Autowired
    QmWmsSkuService qmWmsSkuService;

    @Autowired
    StockoutService stockoutService;

    @Autowired
    StockinService stockinService;

    @Autowired
    ShiporderServiceImpl shiporderServiceImpl;

    @Autowired
    ReturnStockinServiceImpl returnStockinServiceImpl;

    @Autowired
    ReturnStockInCreateService returnStockInCreateService;

    @Autowired
    StockInCreateService stockInCreateService;

    @Autowired
    SysOrderServiceImpl sysOrderServiceImpl;

    @Autowired
    IAfterSaleResendService resendService;

    @Autowired
    InventoryGetService inventoryGetService;

    @Autowired
    QmInventoryQueryService qmInventoryQueryService;

    @Autowired
    ISysReturnService sysReturnService;

    @Autowired
    IProjectManagerService projectManagerService;

    @Value("${qimen.url}")
    private String url;

    @Value("${qimen.appkey}")
    private String appkey;

    @Value("${qimen.secret}")
    private String secret;

    /**
     * OMS调用地址
     */
    @Value("${oms.address}")
    private String omsUrl;

    /**
     * 同步商品接口
     *
     * @throws Exception
     */
    @Override
    public int synchronizeGoods(String shopId, Map<String, Object> paramMap) throws Exception {

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("prj_id", shopId);

        // 获取奇门需要同步的仓库
        List<Stor> storList = storService.selectInfoStorByPrjId(reqMap);
        if (storList == null || storList.size() <= 0) {
            return 1;
        }

        // 获取奇门需要同步的商品
        List<GoodsSynchronize> goodsList = goodsSynchronizeService.selectInfoGoodsSynchronizeByPrjId(reqMap);
        if (goodsList == null || goodsList.size() <= 0) {
            return 1;
        }

        String strQmWmsGuid = "";
        String strSkuId = "";

        // 轮询仓库同步奇门商品
        for (Stor stor : storList) {
            String strQmCustomerid = stor.getQmCustomerid();
            // String strWmsAppkey = stor.getWmsAppkey();
            String strQmOwnercode = stor.getQmOwnercode();
            // String strErpSecretkey = stor.getErpSecretkey();

            //项目环境: normal;sandbox;
            String strEnv = stor.getEnv();//wangxing add 沙箱环境开发

            for (GoodsSynchronize goods : goodsList) {
                // 调用奇门API同步商品
                // taobao.qimen.singleitem.synchronize
                QimenClient client = new DefaultQimenClient(url, appkey, secret);
                SingleitemSynchronizeRequest req = new SingleitemSynchronizeRequest();
                req.setCustomerId(strQmCustomerid);
                req.setVersion("2.0");
                req.setActionType(goods.getActionType());// 商品状态 add, update
                req.setWarehouseCode(goods.getWarehouseCode());// 仓库编码
                req.setOwnerCode(strQmOwnercode);// 货主编码

                com.qimen.api.request.SingleitemSynchronizeRequest.Item item = new com.qimen.api.request.SingleitemSynchronizeRequest.Item();
                item.setItemCode(goods.getItemCode());// 商品编码
                if ("update".equals(goods.getActionType())) {
                    item.setItemId(goods.getItemId());// 仓储系统商品Id
                    strQmWmsGuid = goods.getQmWmsSkuId();// QmWmsSkuId
                }
                item.setItemName(goods.getItemName());// 商品名称
                item.setBarCode(goods.getBarCode());// 条形码
                item.setTitle(goods.getTitle());// 渠道中的商品标题
                item.setCategoryId(goods.getCategoryId());// 商品类别ID
                item.setCategoryName(goods.getCategoryName());// 商品类别名称
                item.setItemType(goods.getItemType());// 商品类型
                item.setRetailPrice(goods.getRetailPrice());// 零售价
                item.setCostPrice(goods.getCostPrice());// 成本价
                item.setRemark(goods.getRemark());// 备注
                item.setCreateTime(goods.getCreateTime());// 创建时间(YYYY-MM-DD
                // HH:MM:SS)
                item.setUpdateTime(goods.getUpdateTime());// 更新时间(YYYY-MM-DD
                // HH:MM:SS)
                item.setIsValid(goods.getIsValid());// 是否有效(Y/N ;默认为N)
                item.setIsSku(goods.getIsSku());// 是否sku(Y/N ;默认为N)
                item.setOriginAddress(goods.getOriginAddress());// 商品的原产地
                item.setEnglishName(goods.getEnglishName());// 英文名
                req.setItem(item);


                SingleitemSynchronizeResponse rsp = null;
                //wangxing add 沙箱环境开发
                if ("sandbox".equals(strEnv)) {
                    rsp = new SingleitemSynchronizeResponse();
                    rsp.setBody("沙箱环境");
                    rsp.setItemId("");
                    rsp.setMessage("沙箱环境");
                } else {
                    //正式环境调用
                    rsp = client.execute(req);
                }


                logUtil.info(new DBLog(goods.getItemCode(), rsp.getBody(), "synchronizeGoods", JSON.toJSONString(req)));

                if ("sandbox".equals(strEnv) || rsp.isSuccess()) {//wangxing add 沙箱环境开发
                    strSkuId = goods.getSkuId();
                    if ("update".equals(goods.getActionType())) {
                        // 更新数据
                        QmWmsSku qmWmsSku = new QmWmsSku();
                        qmWmsSku.setQmWmsSkuId(strQmWmsGuid);
                        qmWmsSku.setLastSyncTime(new Date());
                        qmWmsSkuService.updateByPrimaryKeySelectiveQmWmsSku(qmWmsSku);
                        // 插入操作日志
                        logUtil.info(new DBLog(goods.getItemCode(), "", "synchronizeGoods", DateUtil.getCurrentDateStr()
                                + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的商品【" + goods.getItemCode() + "】同步成功(修改)"));
                    } else {
                        // 插入数据
                        QmWmsSku qmWmsSku = new QmWmsSku();
                        qmWmsSku.setQmWmsSkuId(SnoGerUtil.getUUID());
                        qmWmsSku.setQmCustomerId(stor.getQmCustomerid());
                        qmWmsSku.setSkuId(strSkuId);

                        //wangxing add 沙箱环境开发
                        if ("sandbox".equals(strEnv)) {
                            qmWmsSku.setItemId(goods.getItemCode());
                        } else if (rsp.isSuccess()) {
                            qmWmsSku.setItemId(rsp.getItemId());
                        }

                        qmWmsSku.setLastSyncTime(new Date());
                        qmWmsSkuService.insertSelectiveQmWmsSku(qmWmsSku);
                        // 插入操作日志
                        logUtil.info(new DBLog(goods.getItemCode(), "", "synchronizeGoods", DateUtil.getCurrentDateStr()
                                + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的商品【" + goods.getItemCode() + "】同步成功(新增)"));
                    }
                } else {
                    // 插入失败操作日志
                    logUtil.info(new DBLog(goods.getItemCode(), "", "synchronizeGoods",
                            DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的商品【" + goods.getItemCode()
                                    + "】同步失败, 原因: " + rsp.getMessage() + ""));
                }
            }
        }
        return 1;
    }

    /**
     * 其他出库单创建接口
     *
     * @throws Exception
     */
    @Override
    public int otherStockoutCreate(String shopId, Map<String, Object> paramMap) throws Exception {

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("prj_id", shopId);

        // 获取奇门需要同步的仓库
        List<Stor> storList = storService.selectInfoStorByPrjId(reqMap);
        if (storList == null || storList.size() <= 0) {
            return 1;
        }

        // 轮询仓库同步奇门商品
        for (Stor stor : storList) {
            String strQmCustomerid = stor.getQmCustomerid();// 奇门货主Id
            String strQmOwnercode = stor.getQmOwnercode();// 奇门货主编码
            String strEntId = stor.getEntId();
            String strStorId = stor.getStorId();
            String strTel = stor.getTel();
            String strMobile = stor.getMobile();
            String strAddr = stor.getAddr();
            String strPostCode = stor.getPostCode();
            String strProvName = stor.getProvName();
            String strCityName = stor.getCityName();
            String strDistName = stor.getDistName();

            //项目环境: normal;sandbox;
            String strEnv = stor.getEnv();//wangxing add 沙箱环境开发

            reqMap.put("stor_id", strStorId);

            // 获取需要创建的其他发货单信息
            List<OtherStockoutCreate> otherStockoutList = otherStockoutCreateService.selectInfoOtherStockoutByPrjIdAndStorId(reqMap);
            if (otherStockoutList == null || otherStockoutList.size() <= 0) {
                continue;
            }

            for (OtherStockoutCreate otherStockout : otherStockoutList) {

                String strStockoutId = otherStockout.getDeliveryOrderCode();// 出库单Id
                String strStockoutCode = otherStockout.getStockoutCode();// 出库单编号

                // 调用奇门API创建其他出库单
                // taobao.qimen.stockout.create
                QimenClient client = new DefaultQimenClient(url, appkey, secret);
                StockoutCreateRequest req = new StockoutCreateRequest();
                req.setCustomerId(strQmCustomerid);
                req.setVersion("2.0");

                StockoutCreateRequest.DeliveryOrder deliveryOrder = new StockoutCreateRequest.DeliveryOrder();

                deliveryOrder.setDeliveryOrderCode(otherStockout.getStockoutCode());// 出库单号
                deliveryOrder.setOrderType(otherStockout.getOrderType());// 出库单类型
                deliveryOrder.setWarehouseCode(otherStockout.getWarehouseCode());// 仓库编码
                deliveryOrder.setCreateTime(otherStockout.getCreateTime());// 出库单创建时间
                deliveryOrder.setLogisticsCode(otherStockout.getLogisticsCode());// 物流公司编码
                deliveryOrder.setRemark(otherStockout.getRemark());// 备注

                // 发件方
                StockoutCreateRequest.SenderInfo senderInfo = new StockoutCreateRequest.SenderInfo();
                senderInfo.setName(otherStockout.getSname());// 姓名
                senderInfo.setZipCode(strPostCode);// 邮编
                senderInfo.setTel(strTel);// 固定电话
                senderInfo.setMobile(strMobile);// 移动电话
                senderInfo.setProvince(strProvName);// 省份
                senderInfo.setCity(strCityName);// 城市
                senderInfo.setArea(strDistName);// 区域
                senderInfo.setDetailAddress(strAddr);// 详细地址

                deliveryOrder.setSenderInfo(senderInfo);

                // 收件方
                StockoutCreateRequest.ReceiverInfo receiverInfo = new StockoutCreateRequest.ReceiverInfo();
                receiverInfo.setName(otherStockout.getRname());// 姓名
                receiverInfo.setTel(otherStockout.getRtel());// 固定电话
                receiverInfo.setMobile(otherStockout.getRmobile());// 移动电话
                receiverInfo.setProvince(otherStockout.getRprovince());// 省份
                receiverInfo.setCity(otherStockout.getRcity());// 城市
                receiverInfo.setArea(otherStockout.getRarea());// 区域
                receiverInfo.setDetailAddress(otherStockout.getRdetailAddress());// 详细地址

                deliveryOrder.setReceiverInfo(receiverInfo);

                req.setDeliveryOrder(deliveryOrder);

                // 其它出库单商品明细信息接口参数的赋值
                List<StockoutCreateRequest.OrderLine> orderLines = new ArrayList<StockoutCreateRequest.OrderLine>();

                // 获取需要创建的其他出库单商品信息
                Map<String, Object> reqMapSku = new HashMap<String, Object>();
                reqMapSku.put("stockout_id", strStockoutId);

                List<OtherStockoutSkuCreate> otherStockoutSkuList = otherStockoutCreateService
                        .selectInfoOtherStockoutSkuByStockoutId(reqMapSku);
                if (otherStockoutSkuList == null || otherStockoutSkuList.size() <= 0) {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strStockoutCode, "", "otherStockoutCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的其它出库单【" + strStockoutCode + "】创建失败, 原因: 没有查询到该其他出库单的商品信息"));
                    continue;
                }

                int intItemId = 0;

                for (OtherStockoutSkuCreate otherStockoutSku : otherStockoutSkuList) {
                    StockoutCreateRequest.OrderLine orderLine = new StockoutCreateRequest.OrderLine();

                    orderLine.setOrderLineNo(otherStockoutSku.getOrderLineNo());// 单据行号
                    orderLine.setOwnerCode(strQmOwnercode);// 货主编码
                    orderLine.setItemCode(otherStockoutSku.getItemCode());// 商品编码
                    orderLine.setItemId(otherStockoutSku.getItemId());// 仓储系统商品编码
                    orderLine.setItemName(otherStockoutSku.getItemName());// 商品名称
                    orderLine.setPlanQty(String.valueOf(otherStockoutSku.getPlanQty()));// 应发商品数量
                    orderLine.setInventoryType(otherStockoutSku.getInventoryType());// 库存类型

                    orderLines.add(orderLine);

                    if (StringUtils.isBlank(otherStockoutSku.getItemId())) {
                        intItemId = 1;
                    }
                }

                if (intItemId == 1) {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strStockoutCode, "", "otherStockoutCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的其它出库单【" + strStockoutCode + "】创建失败, 原因: 该其他出库单的商品,仓储系统商品编码不存在"));
                    continue;
                }

                req.setOrderLines(orderLines);

                // 二次校验其他出库单单，未取消、未拿走、未锁定
                Map<String, Object> reqMapCheck = new HashMap<String, Object>();
                reqMapCheck.put("prj_id", shopId);
                reqMapCheck.put("stor_id", strStorId);
                reqMapCheck.put("stockout_id", strStockoutId);

                List<OtherStockoutCreate> otherStockoutCheckList = otherStockoutCreateService
                        .selectInfoOtherStockoutByPrjIdAndStorId(reqMapCheck);
                if (otherStockoutCheckList == null || otherStockoutCheckList.size() <= 0) {
                    // 插入失败操作日志
                    logUtil.info(new DBLog(strStockoutCode, "", "otherStockoutCreate", DateUtil.getCurrentDateStr()
                            + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的其它出库单【" + strStockoutCode + "】创建失败, 原因:  该其他出库单状态已改变"));
                    continue;
                }

                StockoutCreateResponse rsp = null;
                //wangxing add 沙箱环境开发
                if ("sandbox".equals(strEnv)) {
                    rsp = new StockoutCreateResponse();
                    rsp.setBody("沙箱环境");
                    rsp.setDeliveryOrderId("");
                    rsp.setMessage("沙箱环境");
                } else {
                    //正式环境调用
                    rsp = client.execute(req);
                }

                logUtil.info(new DBLog(strStockoutCode, rsp.getBody(), "otherStockoutCreate", JSON.toJSONString(req)));

                if ("sandbox".equals(strEnv) || rsp.isSuccess()) {

                    //wangxing add 沙箱环境开发
                    String strDeliveryOrderId = "";
                    if ("sandbox".equals(strEnv)) {
                        strDeliveryOrderId = strStockoutCode;// 出库单仓储系统编码
                    } else if (rsp.isSuccess()) {
                        strDeliveryOrderId = rsp.getDeliveryOrderId();// 出库单仓储系统编码
                    }

                    // strDeliveryOrderId返回的参数是空值
                    if (StringUtils.isBlank(strDeliveryOrderId)) {

                        // 插入失败操作日志
                        logUtil.info(new DBLog(strStockoutCode, "", "otherStockoutCreate",
                                DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的其它出库单【" + strStockoutCode
                                        + "】创建失败, 原因: deliveryOrderId 没有返回值"));
                        continue;
                    }

                    // 其它出库单创建成功后，库存等的操作
                    for (OtherStockoutSkuCreate otherStockoutSku : otherStockoutSkuList) {

                        StockVO stockVO = new StockVO();
                        stockVO.setSourceCode(strStockoutCode);
                        stockVO.setEntId(strEntId);
                        stockVO.setStorId(strStorId);
                        stockVO.setPrjId(shopId);
                        stockVO.setSkuId(otherStockoutSku.getSkuId());
                        // stockVO.setTotalCount(otherStockoutSku.getPlanQty()
                        // * -1);
                        stockVO.setSellCount(otherStockoutSku.getPlanQty() * -1);
                        // stockVO.setLogicStockoutQty(otherStockoutSku.getPlanQty());
                        stockVO.setAllotQty(otherStockoutSku.getPlanQty() * -1);
                        stockVO.setTag("奇门其它出库单创建");

                        // zp=正品;cc=残次
                        if ("zp".equals(otherStockoutSku.getInventoryType())) {
                            stockVO.setSellCount(otherStockoutSku.getPlanQty() * -1);
                        } else {
                            stockVO.setJunkCount(otherStockoutSku.getPlanQty() * -1);
                        }

                        // 请求地址
                        String requestUrl = omsUrl + "stock/updateStock.action";
                        // 请求参数拼接
                        String requestParams = JSON.toJSONString(stockVO);

                        // 请求数据,操作库存相关信息
                        String resJson = HttpUtils.sendByPostJson(requestUrl, requestParams);

                        // 转换响应数据
                        Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);
                        if (resultMap != null && resultMap.size() > 0) {
                            if (resultMap.containsKey("result") && "success".equals(resultMap.get("result"))) {
                            }
                        }
                    }

                    // 更新其它出库单数据
                    Stockout stockout = new Stockout();
                    stockout.setStockoutId(strStockoutId);
                    stockout.setWmsStockoutCode(strDeliveryOrderId);
                    stockoutService.updateByPrimaryKeySelectiveStockout(stockout);

                    // 插入操作日志
                    logUtil.info(new DBLog(strStockoutCode, "", "otherStockoutCreate", DateUtil.getCurrentDateStr()
                            + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的其它出库单【" + strStockoutCode + "】创建成功"));

                } else {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strStockoutCode, "", "otherStockoutCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的其它出库单【" + strStockoutCode + "】创建失败, 原因: " + rsp.getMessage() + ""));
                }

            }
        }
        return 1;
    }

    /**
     * 奇门取消退货入库单接口
     *
     * @param returnStockInVO 退货入库单VO
     * @return 结果Map
     * @throws Exception 异常
     */
    @Override
    public int cancelReturnStockin(ReturnStockinVO returnStockInVO) throws Exception {
        int returenResult = 0;

        //wangxing add 沙箱环境开发
        String strEnv = "";
        //通过项目ID 获取当前项目环境  normal;sandbox;
        if (returnStockInVO != null && StringUtils.isNotBlank(returnStockInVO.getPrjId())) {
            ProjectVO projectVO = projectManagerService.findProjectById(returnStockInVO.getPrjId());
            if (projectVO != null) {
                strEnv = projectVO.getEnv();
            }
        } else {
            logUtil.error(new DBLog("", "", "cancelReturnStockin", "获取单据项目ID错误"));
            return 0;
        }


        // 调用奇门接口
        // taobao.qimen.order.cancel
        QimenClient client = new DefaultQimenClient(url, appkey, secret);
        OrderCancelRequest req = new OrderCancelRequest();
        req.setOrderCode(returnStockInVO.getStockinCode());
        req.setOrderType("THRK");
        req.setWarehouseCode(returnStockInVO.getStorCode());
        req.setOwnerCode(returnStockInVO.getQmOwnercode());
        req.setOrderId(returnStockInVO.getWmsStockinCode());
        req.setCustomerId(returnStockInVO.getQmCustomerid());

        OrderCancelResponse rsp = null;
        //wangxing add 沙箱环境开发
        if ("sandbox".equals(strEnv)) {
            rsp = new OrderCancelResponse();
            rsp.setBody("沙箱环境");
            rsp.setMessage("沙箱环境");
        } else {
            //正式环境调用
            rsp = client.execute(req);
        }

        logUtil.info(new DBLog(returnStockInVO.getStockinCode(), rsp.getBody(), "cancelReturnStockin", JSON.toJSONString(req)));


        ReturnStockinVO returnStockinData = new ReturnStockinVO();
        if ("sandbox".equals(strEnv) || rsp.isSuccess()) {
            // 更新退货入库单
            returnStockinData.setStockinId(returnStockInVO.getStockinId());
            returnStockinData.setCancelStatus("y");
            returnStockinData.setCancelRemark("");
            returnStockinServiceImpl.updateReturnStockin(returnStockinData);

            logUtil.info(new DBLog(returnStockInVO.getStockinCode(), "", "cancelReturnStockin", DateUtil.getCurrentDateStr()
                    + " 奇门任务对奇门货主编码为【" + returnStockInVO.getQmOwnercode() + "】下的退货入库单【" + returnStockInVO.getStockinCode() + "】取消成功"));

            returenResult = 1;
        } else {
            // 更新退货入库单
            returnStockinData.setStockinId(returnStockInVO.getStockinId());
            returnStockinData.setCancelStatus("f");
            returnStockinData.setCancelRemark(rsp.getMessage());
            returnStockinServiceImpl.updateReturnStockin(returnStockinData);

            logUtil.info(new DBLog(returnStockInVO.getStockinCode(), "", "cancelReturnStockin",
                    DateUtil.getCurrentDateStr() + " 奇门任务对奇门货主编码为【" + returnStockInVO.getQmOwnercode() + "】下的退货入库单【"
                            + returnStockInVO.getStockinCode() + "】取消失败, 原因: " + rsp.getMessage() + ""));

            returenResult = 0;
        }

        // 更新退货单状态为待审核
        if ("sandbox".equals(strEnv) || rsp.isSuccess()) {
            SysReturnVO sysReturnVO = new SysReturnVO();
            sysReturnVO.setReturnId(returnStockInVO.getSourceId());
            sysReturnVO.setReturnStatus("a");
            sysReturnService.updateSysReturn(sysReturnVO);
        }

        return returenResult;
    }

    /**
     * 奇门取消发货单
     *
     * @param shiporderVO 发货单VO
     * @return 结果Map
     * @throws Exception 异常
     */
    @SuppressWarnings("unchecked")
    private int qimenCancelShiporder(ShiporderVO shiporderVO) throws Exception {

        //wangxing add 沙箱环境开发
        String strEnv = "";
        //通过项目ID 获取当前项目环境  normal;sandbox;
        if (shiporderVO != null && StringUtils.isNotBlank(shiporderVO.getPrjId())) {
            ProjectVO projectVO = projectManagerService.findProjectById(shiporderVO.getPrjId());
            if (projectVO != null) {
                strEnv = projectVO.getEnv();
            }
        } else {
            logUtil.error(new DBLog("", "", "cancelShiporder", "获取单据项目ID错误"));
            return 0;
        }


        // 调用奇门接口
        // taobao.qimen.order.cancel
        QimenClient client = new DefaultQimenClient(url, appkey, secret);
        OrderCancelRequest req = new OrderCancelRequest();
        req.setOrderCode(shiporderVO.getShiporderCode());
        if ("or".equals(shiporderVO.getSourceType())) {
            req.setOrderType("JYCK");
        } else {
            req.setOrderType("BFCK");
        }
        req.setWarehouseCode(shiporderVO.getStorCode());
        req.setOwnerCode(shiporderVO.getQmOwnercode());
        req.setOrderId(shiporderVO.getWmsShiporderCode());
        req.setCustomerId(shiporderVO.getQmCustomerid());

        OrderCancelResponse rsp = null;
        //wangxing add 沙箱环境开发
        if ("sandbox".equals(strEnv)) {
            rsp = new OrderCancelResponse();
            rsp.setBody("沙箱环境");
            rsp.setMessage("沙箱环境");
        } else {
            //正式环境调用
            rsp = client.execute(req);
        }

        logUtil.info(new DBLog(shiporderVO.getShiporderCode(), rsp.getBody(), "cancelShiporder", JSON.toJSONString(req)));

        ShiporderVO shiporderData = new ShiporderVO();
        if ("sandbox".equals(strEnv) || rsp.isSuccess()) {
            // 操作发货单
            shiporderData.setShiporderId(shiporderVO.getShiporderId());
            shiporderData.setCancelStatus("y");
            shiporderData.setCancelRemark("");
            shiporderServiceImpl.updateShiporder(shiporderData);

            // 操作库存
            ShiporderSku shiporderSku = new ShiporderSku();
            shiporderSku.setShiporderId(shiporderVO.getShiporderId());
            List<ShiporderSku> shiporderSkuDataList = shiporderServiceImpl.selectByVOShiporderSku(shiporderSku);
            List<SysOrderGoods> sysOrderGoodsList = new ArrayList<SysOrderGoods>();
            for (ShiporderSku shiporderSkuData : shiporderSkuDataList) {
                StockVO stockVO = new StockVO();
                stockVO.setEntId(shiporderVO.getEntId());
                stockVO.setStorId(shiporderVO.getStorId());
                stockVO.setPrjId(shiporderVO.getPrjId());
                stockVO.setSkuId(shiporderSkuData.getSkuId());
                stockVO.setSourceCode(shiporderVO.getShiporderCode());
                stockVO.setTag("奇门取消发货单");
                stockVO.setUnallotQty(shiporderSkuData.getQty());
                stockVO.setLogicStockoutQty(shiporderSkuData.getQty() * -1);
                stockVO.setSellCount(shiporderSkuData.getQty());
                // 请求地址
                String requestUrl = omsUrl + "stock/updateStock.action";
                // 请求参数拼接
                String requestParams = JSON.toJSONString(stockVO);
                // 请求数据,操作库存相关信息
                String resJson = HttpUtils.sendByPostJson(requestUrl, requestParams);
                // 转换响应数据
                Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);
                if (resultMap != null && "n".equals(resultMap.get("result"))) {
                    logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "cancelShiporder",
                            DateUtil.getCurrentDateStr() + "  奇门自动任务对奇门货主编码为【" + shiporderVO.getQmOwnercode() + "】下的发货单【"
                                    + shiporderVO.getShiporderCode() + "】取消失败, 原因: 更新库存失败，" + resultMap.get("msg") + ""));
                }

                // 构建订单数据
                if ("or".equals(shiporderVO.getSourceType())) {
                    SysOrderGoods sysOrderGoods = new SysOrderGoods();
                    sysOrderGoods.setOrderGoodsId(shiporderSkuData.getOrderSkuId());
                    sysOrderGoods.setShippingQty(shiporderSkuData.getQty() * -1);
                    sysOrderGoodsList.add(sysOrderGoods);
                }
            }

            logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "cancelShiporder", DateUtil.getCurrentDateStr() + "  来源类型：" + shiporderVO.getSourceType() + " 来源id：" + shiporderVO.getSourceId()));

            if ("or".equals(shiporderVO.getSourceType())) { // 操作订单
                SysOrderVO sysOrderData = new SysOrderVO();
                sysOrderData.setOrderId(shiporderVO.getSourceId());
                sysOrderData.setOrderStatus("i");
                sysOrderData.setLockRemark("自动任务-奇门取消发货单，订单打回待分派");
                sysOrderData.setLockTime(new Date());
                sysOrderServiceImpl.updateLockOrder(sysOrderData);

                for (SysOrderGoods sysOrderGoods : sysOrderGoodsList) {
                    sysOrderServiceImpl.updateByPrimaryKeySelectiveSysOrderGoods(sysOrderGoods);
                }

                logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "cancelShiporder", DateUtil.getCurrentDateStr() + "  奇门任务操作订单"));
            } else { // 操作补发单
                AfterSaleResend record = new AfterSaleResend();
                record.setResendId(shiporderVO.getSourceId());
                record.setResendStatus("a");
                resendService.updateResend(record);

                logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "cancelShiporder", DateUtil.getCurrentDateStr() + "  奇门任务操作补发单"));
            }

            logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "cancelShiporder", DateUtil.getCurrentDateStr()
                    + "  奇门任务对奇门货主编码为【" + shiporderVO.getQmOwnercode() + "】下的发货单【" + shiporderVO.getShiporderCode() + "】取消成功"));

            return 1;
        } else {
            // 操作发货单
            shiporderData.setShiporderId(shiporderVO.getShiporderId());
            shiporderData.setCancelStatus("f");
            shiporderData.setCancelRemark(rsp.getMessage());
            shiporderServiceImpl.updateShiporder(shiporderData);

            logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "cancelShiporder",
                    DateUtil.getCurrentDateStr() + "  奇门自动任务对奇门货主编码为【" + shiporderVO.getQmOwnercode() + "】下的发货单【"
                            + shiporderVO.getShiporderCode() + "】取消失败, 原因: " + rsp.getMessage() + ""));

            return 0;
        }
    }

    /**
     * 手动取消发货单
     *
     * @throws Exception
     */
    @Override
    public int manualCancelShiporder(ShiporderVO shiporderVO) throws Exception {
        return qimenCancelShiporder(shiporderVO);
    }

    /**
     * 自动取消发货单
     *
     * @throws Exception
     */
    @Override
    public int autoCancelShiporder(String shopId, Map<String, Object> paramMap) throws Exception {
        int returenResult = 0;

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("prj_id", shopId);

        // 获取奇门需要同步的仓库
        List<Stor> storList = storService.selectInfoStorByPrjId(reqMap);
        if (storList == null || storList.size() <= 0) {
            logUtil.info(new DBLog(shopId, "", "cancelShiporder", DateUtil.getCurrentDateStr() + " 奇门没有需要同步的仓库"));
            return 0;
        }

        // 轮询仓库同步奇门商品
        for (Stor stor : storList) {
            String strStorId = stor.getStorId();

            // 获取需要取消的发货单信息
            ShiporderVO shiporderSelVO = new ShiporderVO();
            shiporderSelVO.setPrjId(shopId);
            shiporderSelVO.setStorId(strStorId);
            List<ShiporderVO> shiporderVOList = shiporderServiceImpl.selectShiporderListForCancel(shiporderSelVO);
            if (shiporderVOList == null || shiporderVOList.size() <= 0) {
                logUtil.info(new DBLog(strStorId, "", "cancelShiporder",
                        DateUtil.getCurrentDateStr() + " 仓库Id【" + strStorId + "】没有可取消的发货单"));
                continue;
            }

            for (ShiporderVO shiporderVO : shiporderVOList) {
                int result = qimenCancelShiporder(shiporderVO);
                if (result != 0) {
                    returenResult = result;
                }

            }
        }

        return returenResult;
    }

    /**
     * 发货单创建接口
     *
     * @throws Exception
     */
    @Override
    public int shipOrderCreate(String shopId, Map<String, Object> paramMap) throws Exception {

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("prj_id", shopId);

        // 获取奇门需要同步的仓库
        List<Stor> storList = storService.selectInfoStorByPrjId(reqMap);
        if (storList == null || storList.size() <= 0) {
            return 1;
        }

        // 轮询仓库同步奇门商品
        for (Stor stor : storList) {
            String strQmCustomerid = stor.getQmCustomerid();// 奇门货主Id
            String strQmOwnercode = stor.getQmOwnercode();// 奇门货主编码
            String strEntId = stor.getEntId();
            String strStorId = stor.getStorId();
            String strTel = stor.getTel();
            String strMobile = stor.getMobile();
            String strAddr = stor.getAddr();
            String strPostCode = stor.getPostCode();
            String strProvName = stor.getProvName();
            String strCityName = stor.getCityName();
            String strDistName = stor.getDistName();

            //项目环境: normal;sandbox;
            String strEnv = stor.getEnv(); //wangxing add 沙箱环境开发

            reqMap.put("stor_id", strStorId);

            // 获取需要创建的发货单信息
            List<ShipOrderCreate> shipOrderList = shipOrderCreateService.selectInfoShipOrderByPrjIdAndStorId(reqMap);
            if (shipOrderList == null || shipOrderList.size() <= 0) {
                continue;
            }

            for (ShipOrderCreate shipOrder : shipOrderList) {

                String strShiporderId = shipOrder.getDeliveryOrderCode();// 出库单Id
                String strShiporderCode = shipOrder.getShiporderCode();// 出库单编号

                // 调用奇门API创建发货单
                // taobao.qimen.deliveryorder.create
                QimenClient client = new DefaultQimenClient(url, appkey, secret);
                DeliveryorderCreateRequest req = new DeliveryorderCreateRequest();
                req.setCustomerId(strQmCustomerid);
                req.setVersion("2.0");

                DeliveryorderCreateRequest.DeliveryOrder deliveryOrder = new DeliveryorderCreateRequest.DeliveryOrder();

                deliveryOrder.setDeliveryOrderCode(shipOrder.getShiporderCode());// 发货单号
                deliveryOrder.setOrderType(shipOrder.getOrderType());// 发货单类型
                deliveryOrder.setWarehouseCode(shipOrder.getWarehouseCode());// 仓库编码
                // deliveryOrder.setSourcePlatformCode(shipOrder.getSourcePlatformCode());//
                // 订单来源平台编码
                deliveryOrder.setCreateTime(shipOrder.getCreateTime());// 发货单创建时间
                deliveryOrder.setPlaceOrderTime(shipOrder.getPlaceOrderTime());// 前台订单/店铺订单的创建时间/下单时间
                deliveryOrder.setPayTime(shipOrder.getPayTime());// 订单支付时间
                deliveryOrder.setOperateTime(shipOrder.getOperateTime());// 操作(审核)时间
                deliveryOrder.setShopNick(shipOrder.getShopNick());// 店铺名称
                deliveryOrder.setTotalAmount(shipOrder.getTotalAmount());// 订单总金额
                deliveryOrder.setLogisticsCode(shipOrder.getLogisticsCode());// 物流公司编码
                deliveryOrder.setExpressCode(shipOrder.getExpressCode());// 运单号
                deliveryOrder.setBuyerMessage(shipOrder.getBuyerMessage());// 买家留言
                deliveryOrder.setSellerMessage(shipOrder.getSellerMessage());// 卖家留言
                deliveryOrder.setRemark(shipOrder.getRemark());// 备注
                deliveryOrder.setOrderFlag(shipOrder.getOrderFlag());// 订单标记
                deliveryOrder.setArAmount(shipOrder.getArAmount());// 应收金额

                // 发件方
                DeliveryorderCreateRequest.SenderInfo senderInfo = new DeliveryorderCreateRequest.SenderInfo();
                senderInfo.setName(shipOrder.getSname());// 姓名
                senderInfo.setZipCode(strPostCode);// 邮编
                senderInfo.setTel(strTel);// 固定电话
                senderInfo.setMobile(strMobile);// 移动电话
                senderInfo.setProvince(strProvName);// 省份
                senderInfo.setCity(strCityName);// 城市
                senderInfo.setArea(strDistName);// 区域
                senderInfo.setDetailAddress(strAddr);// 详细地址

                deliveryOrder.setSenderInfo(senderInfo);

                // 收件方
                DeliveryorderCreateRequest.ReceiverInfo receiverInfo = new DeliveryorderCreateRequest.ReceiverInfo();
                receiverInfo.setName(shipOrder.getRname());// 姓名
                receiverInfo.setTel(shipOrder.getRtel());// 固定电话
                receiverInfo.setMobile(shipOrder.getRmobile());// 移动电话
                receiverInfo.setProvince(shipOrder.getRprovince());// 省份
                receiverInfo.setCity(shipOrder.getRcity());// 城市
                receiverInfo.setArea(shipOrder.getRarea());// 区域
                receiverInfo.setDetailAddress(shipOrder.getRdetailAddress());// 详细地址

                deliveryOrder.setReceiverInfo(receiverInfo);

                req.setDeliveryOrder(deliveryOrder);

                // 发货单商品明细信息接口参数的赋值
                List<DeliveryorderCreateRequest.OrderLine> orderLines = new ArrayList<DeliveryorderCreateRequest.OrderLine>();

                Map<String, Object> reqMapSku = new HashMap<String, Object>();
                reqMapSku.put("shiporder_id", strShiporderId);

                // 获取需要创建的发货单商品信息
                List<ShipOrderSkuCreate> shipOrderSkuList = shipOrderCreateService.selectInfoShipOrderSkuByStockoutId(reqMapSku);
                if (shipOrderSkuList == null || shipOrderSkuList.size() <= 0) {
                    // 插入失败操作日志
                    logUtil.info(new DBLog(strShiporderCode, "", "shipOrderCreate", DateUtil.getCurrentDateStr()
                            + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的发货单【" + strShiporderCode + "】创建失败, 原因: 没有查询到该发货单的商品信息"));
                    continue;
                }

                int intItemId = 0;

                for (ShipOrderSkuCreate shipOrderSku : shipOrderSkuList) {
                    DeliveryorderCreateRequest.OrderLine orderLine = new DeliveryorderCreateRequest.OrderLine();

                    orderLine.setOrderLineNo(shipOrderSku.getOrderLineNo());// 单据行号
                    orderLine.setSourceOrderCode(shipOrderSku.getSourceOrderCode());// 交易平台订单
                    orderLine.setSubSourceOrderCode(shipOrderSku.getSubSourceOrderCode());// 交易平台子订单编码
                    orderLine.setOwnerCode(strQmOwnercode);// 货主编码
                    orderLine.setItemCode(shipOrderSku.getItemCode());// 商品编码
                    orderLine.setItemId(shipOrderSku.getItemId());// 仓储系统商品编码
                    orderLine.setItemName(shipOrderSku.getItemName());// 商品名称
                    orderLine.setPlanQty(String.valueOf(shipOrderSku.getPlanQty()));// 应发商品数量
                    orderLine.setActualPrice(shipOrderSku.getActualPrice());// 实际成交价
                    orderLine.setInventoryType("ZP"); // 商品属性

                    orderLines.add(orderLine);

                    if (StringUtils.isBlank(shipOrderSku.getItemId())) {
                        intItemId = 1;
                    }
                }

                if (intItemId == 1) {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strShiporderCode, "", "shipOrderCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的发货单【" + strShiporderCode + "】创建失败, 原因: 该发货单的商品,仓储系统商品编码不存在"));
                    continue;
                }

                req.setOrderLines(orderLines);

                // 二次校验发货单，未取消、未拿走、未锁定
                Map<String, Object> reqMapCheck = new HashMap<String, Object>();
                reqMapCheck.put("prj_id", shopId);
                reqMapCheck.put("stor_id", strStorId);
                reqMapCheck.put("shiporder_id", strShiporderId);

                List<ShipOrderCreate> shipOrderCheckList = shipOrderCreateService.selectInfoShipOrderByPrjIdAndStorId(reqMapCheck);
                if (shipOrderCheckList == null || shipOrderCheckList.size() <= 0) {
                    // 插入失败操作日志
                    logUtil.info(new DBLog(strShiporderCode, "", "shipOrderCreate", DateUtil.getCurrentDateStr()
                            + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的发货单【" + strShiporderCode + "】创建失败, 原因: 该发货单状态已改变"));
                    continue;
                }

                DeliveryorderCreateResponse rsp = null;
                //wangxing add 沙箱环境开发
                if ("sandbox".equals(strEnv)) {
                    rsp = new DeliveryorderCreateResponse();
                    rsp.setBody("沙箱环境");
                    rsp.setDeliveryOrderId("");
                    rsp.setMessage("沙箱环境");
                } else {
                    //正式环境调用
                    rsp = client.execute(req);
                }

                logUtil.info(new DBLog(strShiporderCode, rsp.getBody(), "shipOrderCreate", JSON.toJSONString(req)));
                if ("sandbox".equals(strEnv) || rsp.isSuccess()) {
                    // 出库单仓储系统编码
                    String strDeliveryOrderId = "";

                    //wangxing add 沙箱环境开发
                    if ("sandbox".equals(strEnv)) {
                        strDeliveryOrderId = strShiporderCode;// 出库单仓储系统编码
                    } else if (rsp.isSuccess()) {
                        strDeliveryOrderId = rsp.getDeliveryOrderId();// 出库单仓储系统编码
                    }

                    // strDeliveryOrderId返回的参数是空值
                    if (StringUtils.isBlank(strDeliveryOrderId)) {

                        // 插入失败操作日志
                        logUtil.info(new DBLog(strShiporderCode, "", "shipOrderCreate",
                                DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的发货单【" + strShiporderCode
                                        + "】创建失败, 原因: deliveryOrderId 没有返回值"));
                        continue;
                    }

                    // 发货单创建成功后，库存等的操作
                    for (ShipOrderSkuCreate shipOrderSku : shipOrderSkuList) {

                        StockVO stockVO = new StockVO();
                        stockVO.setSourceCode(strShiporderCode);
                        stockVO.setEntId(strEntId);
                        stockVO.setStorId(strStorId);
                        stockVO.setPrjId(shopId);
                        stockVO.setSkuId(shipOrderSku.getSkuId());
                        // stockVO.setTotalCount(shipOrderSku.getPlanQty() *
                        // -1);
                        stockVO.setLogicStockoutQty(shipOrderSku.getPlanQty());
                        stockVO.setAllotQty(shipOrderSku.getPlanQty() * -1);
                        stockVO.setSellCount(shipOrderSku.getPlanQty() * -1);
                        stockVO.setTag("奇门发货单创建");

                        // 请求地址
                        String requestUrl = omsUrl + "stock/updateStock.action";
                        // 请求参数拼接
                        String requestParams = JSON.toJSONString(stockVO);

                        // 请求数据,操作库存相关信息
                        String resJson = HttpUtils.sendByPostJson(requestUrl, requestParams);

                        // 转换响应数据
                        Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);
                        if (resultMap != null && resultMap.size() > 0) {
                            if (resultMap.containsKey("result") && "success".equals(resultMap.get("result"))) {
                            }
                        }

                    }

                    // 更新发货单数据
                    ShiporderVO shiporderVo = new ShiporderVO();
                    shiporderVo.setShiporderId(strShiporderId);
                    shiporderVo.setWmsShiporderCode(strDeliveryOrderId);
                    shiporderVo.setHasTaken("y");
                    shiporderServiceImpl.updateShiporder(shiporderVo);

                    // 插入操作日志
                    logUtil.info(new DBLog(strShiporderCode, "", "shipOrderCreate", DateUtil.getCurrentDateStr()
                            + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的发货单【" + strShiporderCode + "】创建成功"));

                } else {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strShiporderCode, "", "shipOrderCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的发货单【" + strShiporderCode + "】创建失败, 原因: " + rsp.getMessage() + ""));
                }

            }
        }

        return 1;
    }

    /**
     * 获取仓库库存(多商品) - 同步库存接口(不支持沙箱测试)
     */
    @Override
    public int getInventory(String shopId, Map<String, Object> paramMap) throws Exception {

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("prj_id", shopId);

        // 获取奇门需要同步的仓库
        List<Stor> storList = storService.selectInfoStorByPrjId(reqMap);
        if (storList == null || storList.size() <= 0) {
            return 1;
        }

        // 轮询仓库调用
        for (Stor stor : storList) {

            String strEntId = stor.getEntId();
            String strStorId = stor.getStorId();
            String strQmCustomerid = stor.getQmCustomerid();
            String strErpSecretkey = stor.getErpSecretkey();


            // ========================目前只对接奇门, 菜鸟后期考虑
            // 获取需要查询库存的商品
            reqMap = new HashMap<String, Object>();
            reqMap.put("stor_id", strStorId);
            List<InventoryGet> invList = inventoryGetService.selectInfoGetInventoryByPrjId(reqMap);

            // 轮询查询商品
            for (InventoryGet inv : invList) {

                // taobao.qimen.inventory.query
                QimenClient client = new DefaultQimenClient(url, appkey, secret);
                InventoryQueryRequest req = new InventoryQueryRequest();
                req.setCustomerId(strQmCustomerid);
                req.setVersion("2.0");

                List<Criteria> cList = new ArrayList<InventoryQueryRequest.Criteria>();
                Criteria criteria = new Criteria();
                criteria.setWarehouseCode(inv.getWarehouseCode());
                criteria.setOwnerCode(inv.getOwnerCode());
                criteria.setItemCode(inv.getItemCode());
                criteria.setItemId(inv.getItemId());
                cList.add(criteria);
                req.setCriteriaList(cList);
                InventoryQueryResponse rsp = client.execute(req);

                logUtil.info(new DBLog(inv.getItemCode(), rsp.getBody(), "getInventory", JSON.toJSONString(req)));

                if (rsp.isSuccess()) {

                    int sellCount = 0; // 可销售数
                    int totalCount = 0; // 总库存数
                    int junkCount = 0; // 废品数

                    // 同步系统库存标记
                    Boolean bTemp = true;
                    List<com.qimen.api.response.InventoryQueryResponse.Item> itemList = rsp.getItems();
                    for (com.qimen.api.response.InventoryQueryResponse.Item item : itemList) {

                        logUtil.info(new DBLog(inv.getItemCode(), "log_debug", "getInventory",
                                "" + itemList.size()));

                        QmInventoryQuery qmInventoryQuery = new QmInventoryQuery();
                        qmInventoryQuery.setWarehouseCode(item.getWarehouseCode()); // 仓库编码
                        qmInventoryQuery.setItemCode(item.getItemCode()); // 商品编码
                        qmInventoryQuery.setItemId(item.getItemId());// 仓储系统商品ID
                        qmInventoryQuery.setInventoryType(item.getInventoryType());// 库存类型
                        if (item.getQuantity() != null) {
                            qmInventoryQuery.setQuantity(item.getQuantity().intValue());// 未冻结库存数量
                        }

                        if (item.getLockQuantity() != null) {
                            qmInventoryQuery.setLockQuantity(item.getLockQuantity().intValue()); // 冻结库存数量
                        }

                        qmInventoryQuery.setBatchCode(item.getBatchCode());// 批次编码

                        if (StringUtils.isNotBlank(item.getProductDate())) {
                            qmInventoryQuery.setProductDate(simpleDateFormat.parse(item.getProductDate()));// 商品生产日期
                        }

                        if (StringUtils.isNotBlank(item.getExpireDate())) {
                            qmInventoryQuery.setExpireDate(simpleDateFormat.parse(item.getExpireDate()));// 商品过期日期
                        }

                        qmInventoryQuery.setProduceCode(item.getProduceCode());// 生产批号
                        qmInventoryQuery.setQmCustomerId(strQmCustomerid); // QmCustomerid

                        // 验证是否存在
                        Map<String, Object> selectMap = new HashMap<String, Object>();
                        selectMap.put("warehouse_code", item.getWarehouseCode());
                        selectMap.put("item_code", item.getItemCode());
                        selectMap.put("item_id", item.getItemId());
                        selectMap.put("inventory_type", item.getInventoryType());
                        selectMap.put("batch_code",item.getBatchCode());
                        // 获取QmInventoryQueryId
                        String strQmInventoryQueryId = qmInventoryQueryService.selectByPrimaryKeyQmInventoryQueryId(selectMap);

                        int iExec = 0;
                        if (StringUtils.isBlank(strQmInventoryQueryId)) {
                            // 插入
                            qmInventoryQuery.setQmInventoryQueryId(SnoGerUtil.getUUID());
                            iExec = qmInventoryQueryService.insertSelectiveQmInventoryQuery(qmInventoryQuery);

                        } else {
                            // 更新
                            qmInventoryQuery.setQmInventoryQueryId(strQmInventoryQueryId);
                            iExec = qmInventoryQueryService.updateByPrimaryKeySelectiveQmInventoryQuery(qmInventoryQuery);
                        }

                        // 操作成功
                        if (iExec > 0) {

                            int iQuantity = item.getQuantity() == null ? 0 : item.getQuantity().intValue();
                            int iLockQuantity = item.getLockQuantity() == null ? 0 : item.getLockQuantity().intValue();

                            // 计算库存 默认: 正品
                            if (StringUtils.isBlank(item.getInventoryType()) || "ZP".equals(item.getInventoryType())) {
                                // 正品
                                totalCount = totalCount + iQuantity;
                                sellCount = sellCount + iQuantity;
                            }

                            if ("CC".equals(item.getInventoryType())) {
                                // 残次
                                totalCount = totalCount + iQuantity + iLockQuantity;
                                junkCount = junkCount + iQuantity + iLockQuantity;
                            }
                        } else {
                            bTemp = false;
                        }
                    }
                    // 操作全部成功
                    if (bTemp) {
                        // 同步库存
                        StockVO stockVO = new StockVO();
                        stockVO.setEntId(strEntId);
                        stockVO.setStorId(strStorId);
                        stockVO.setSkuId(inv.getSkuId());
                        stockVO.setSellCount(sellCount);
                        stockVO.setTotalCount(totalCount);
                        stockVO.setJunkCount(junkCount);
                        stockVO.setTag("奇门库存查询");

                        // 请求地址
                        String requestUrl = omsUrl + "stock/updateStock2.action";
                        // 请求参数拼接
                        String requestParams = JSON.toJSONString(stockVO);
                        // 请求数据,操作库存相关信息
                        String resJson = HttpUtils.sendByPostJson(requestUrl, requestParams);
                        // 转换响应数据
                        Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);

                        logUtil.info(new DBLog(inv.getItemCode(), "log_debug", "getInventory",
                                JSON.toJSONString(stockVO) + "/r/n" + JSON.toJSONString(resultMap)));

                        if (resultMap != null && resultMap.size() > 0) {
                            if (resultMap.containsKey("result") && "success".equals(resultMap.get("result"))) {
                            }
                        }
                    }
                    // 插入成功操作日志
                    logUtil.info(new DBLog(inv.getItemCode(), "log_success", "getInventory",
                            DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的获取仓库库存(多商品)任务成功"));

                } else {
                    // 插入失败操作日志
                    logUtil.info(new DBLog(inv.getItemCode(), "log_error", "getInventory", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                            + strQmCustomerid + "】下的获取仓库库存(多商品)任务失败, 原因: " + rsp.getMessage() + ""));
                }
            }
        }
        return 1;
    }

    /**
     * 退货入库单创建接口
     *
     * @throws Exception
     */
    @Override
    public int returnOrderCreate(String shopId, Map<String, Object> paramMap) throws Exception {

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("prj_id", shopId);

        // 获取奇门需要同步的仓库
        List<Stor> storList = storService.selectInfoStorByPrjId(reqMap);
        if (storList == null || storList.size() <= 0) {
            return 1;
        }

        // 轮询仓库同步奇门商品
        for (Stor stor : storList) {
            String strQmCustomerid = stor.getQmCustomerid();// 奇门货主Id
            String strQmOwnercode = stor.getQmOwnercode();// 奇门货主编码
            String strStorId = stor.getStorId();

            //项目环境: normal;sandbox;
            String strEnv = stor.getEnv(); //wangxing add 沙箱环境开发

            reqMap.put("stor_id", strStorId);

            // 获取需要创建的退货入库单信息
            List<ReturnStockInCreate> returnStockInIdList = returnStockInCreateService
                    .selectInfoReturnStockInIdByPrjIdAndStorId(reqMap);
            if (returnStockInIdList == null || returnStockInIdList.size() <= 0) {
                continue;
            }

            for (ReturnStockInCreate returnStockInId : returnStockInIdList) {

                String strStockinId = returnStockInId.getStockinId();// 入库单Id

                reqMap.put("stockin_id", strStockinId);

                ReturnStockInCreate returnStockIn = returnStockInCreateService.selectInfoReturnStockInByPrjIdAndStorId(reqMap);

                if (returnStockIn == null) {
                    continue;
                }

                String strStockInCode = returnStockIn.getReturnOrderCode();// 入库单编号

                // 调用奇门API创建退货入库单
                // taobao.qimen.returnorder.create
                QimenClient client = new DefaultQimenClient(url, appkey, secret);
                ReturnorderCreateRequest req = new ReturnorderCreateRequest();
                req.setCustomerId(strQmCustomerid);
                req.setVersion("2.0");

                ReturnorderCreateRequest.ReturnOrder returnOrder = new ReturnorderCreateRequest.ReturnOrder();

                returnOrder.setReturnOrderCode(returnStockIn.getReturnOrderCode());
                returnOrder.setWarehouseCode(returnStockIn.getWarehouseCode());
                returnOrder.setOrderType("THRK");
                returnOrder.setExpressCode(returnStockIn.getExpressCode());
                returnOrder.setLogisticsName(returnStockIn.getLogisticsName());
                returnOrder.setLogisticsCode(returnStockIn.getLogisticsCode());
                returnOrder.setReturnReason(returnStockIn.getReturnReason());
                returnOrder.setRemark(returnStockIn.getRemark());
                returnOrder.setBuyerNick(returnStockIn.getBuyerNick());
                returnOrder.setPreDeliveryOrderCode(returnStockIn.getPreDeliveryOrderCode());

                ReturnorderCreateRequest.SenderInfo senderInfo = new ReturnorderCreateRequest.SenderInfo();

                senderInfo.setName(returnStockIn.getSname());
                senderInfo.setMobile(returnStockIn.getMobile());
                senderInfo.setDetailAddress(returnStockIn.getDetailAddress());
                senderInfo.setProvince(returnStockIn.getProvince());
                senderInfo.setCity(returnStockIn.getCity());
                senderInfo.setArea(returnStockIn.getArea());

                returnOrder.setSenderInfo(senderInfo);

                req.setReturnOrder(returnOrder);

                // 退货入库单商品明细信息接口参数的赋值
                List<ReturnorderCreateRequest.OrderLine> orderLines = new ArrayList<ReturnorderCreateRequest.OrderLine>();

                Map<String, Object> reqMapSku = new HashMap<String, Object>();
                reqMapSku.put("stockin_id", strStockinId);

                // 获取需要创建的退货入库单商品信息
                List<ReturnStockInSkuCreate> returnStockInSkuList = returnStockInCreateService
                        .selectInfoReturnStockInSkuByStockId(reqMapSku);
                if (returnStockInSkuList == null || returnStockInSkuList.size() <= 0) {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strStockInCode, "", "returnOrderCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的退货入库单【" + strStockInCode + "】创建失败, 原因: 没有查询到该退货入库单的商品信息"));
                    continue;
                }

                for (ReturnStockInSkuCreate returnStockInSku : returnStockInSkuList) {
                    ReturnorderCreateRequest.OrderLine orderLine = new ReturnorderCreateRequest.OrderLine();
                    orderLine.setOrderLineNo(returnStockInSku.getOrderLineNo());// 单据行号
                    orderLine.setOwnerCode(strQmOwnercode);// 货主编码
                    orderLine.setItemCode(returnStockInSku.getItemCode());// 商品编码
                    orderLine.setItemId(returnStockInSku.getItemId());// 仓储系统商品编码
                    orderLine.setPlanQty(returnStockInSku.getQty());// 应收商品数量
                    orderLine.setInventoryType(returnStockInSku.getInventoryType());// 库存类型

                    orderLines.add(orderLine);
                }

                req.setOrderLines(orderLines);


                ReturnorderCreateResponse rsp = null;
                //wangxing add 沙箱环境开发
                if ("sandbox".equals(strEnv)) {
                    rsp = new ReturnorderCreateResponse();
                    rsp.setBody("沙箱环境");
                    rsp.setReturnOrderId("");
                    rsp.setMessage("沙箱环境");
                } else {
                    //正式环境调用
                    rsp = client.execute(req);
                }

                logUtil.info(new DBLog(strStockInCode, rsp.getBody(), "returnOrderCreate", JSON.toJSONString(req)));

                if ("sandbox".equals(strEnv) || rsp.isSuccess()) {
                    // 仓储系统退货单编码
                    String strReturnOrderId = "";

                    //wangxing add 沙箱环境开发
                    if ("sandbox".equals(strEnv)) {
                        strReturnOrderId = strStockInCode;// 仓储系统退货单编码
                    } else if (rsp.isSuccess()) {
                        strReturnOrderId = rsp.getReturnOrderId();// 仓储系统退货单编码
                    }

                    // strReturnOrderId返回的参数是空值
                    if (StringUtils.isBlank(strReturnOrderId)) {

                        // 插入失败操作日志
                        logUtil.info(new DBLog(strStockInCode, "", "returnOrderCreate",
                                DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的退货入库单【" + strStockInCode
                                        + "】创建失败, 原因: returnOrderId 没有返回值"));
                        continue;
                    }

                    // 更新入库单数据
                    Stockin stockin = new Stockin();
                    stockin.setStockinId(strStockinId);
                    stockin.setWmsStockinCode(strReturnOrderId);
                    int iRes = stockinService.updateByPrimaryKeySelectiveStockin(stockin);
                    if (iRes > 0) {
                        // 插入操作日志
                        logUtil.info(new DBLog(strStockInCode, "", "returnOrderCreate", DateUtil.getCurrentDateStr()
                                + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的退货入库单【" + strStockInCode + "】创建成功"));


//移动加权成本价计算 2018-1-12 wangxing add begin ------------------------------------------------------------------------------------------
//                        //更新退货入库单商品成本价
//                        for (ReturnStockInSkuCreate returnStockInSku : returnStockInSkuList) {
//                            //获取系统规格 即时成本价
//                            GoodsSynchronize goodsSkuTemp = returnStockInCreateService.selectGoodsSkuCostBySkuId(returnStockInSku.getSkuId());
//                            if (goodsSkuTemp != null) {
//                                StockinSku stockinSkuTemp = new StockinSku();
//                                stockinSkuTemp.setStockinSkuId(returnStockInSku.getOrderLineNo());
//                                stockinSkuTemp.setGoodsSkuCost(goodsSkuTemp.getGoodsSkuCost());
//                                stockinSkuTemp.setUpdateTime(new Date());
//                                int iStockinSkuUpdate = stockinService.updateStockinSkuById(stockinSkuTemp);
//                            }
//                        }
//移动加权成本价计算 2018-1-12 wangxing add end --------------------------------------------------------------------------------------------


                    }

                } else {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strStockInCode, "", "returnOrderCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的退货入库单【" + strStockInCode + "】创建失败, 原因: " + rsp.getMessage() + ""));
                }
            }
        }
        return 1;
    }

    /**
     * 入库单创建接口
     *
     * @throws Exception
     */
    @Override
    public int entryOrderCreate(String shopId, Map<String, Object> paramMap) throws Exception {

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("prj_id", shopId);

        // 获取奇门需要同步的仓库
        List<Stor> storList = storService.selectInfoStorByPrjId(reqMap);
        if (storList == null || storList.size() <= 0) {
            return 1;
        }

        // 轮询仓库同步奇门商品
        for (Stor stor : storList) {
            String strQmCustomerid = stor.getQmCustomerid();// 奇门货主Id
            String strQmOwnercode = stor.getQmOwnercode();// 奇门货主编码
            String strEntId = stor.getEntId();
            String strStorId = stor.getStorId();
            String strTel = stor.getTel();
            String strMobile = stor.getMobile();
            String strAddr = stor.getAddr();
            String strPostCode = stor.getPostCode();
            String strProvName = stor.getProvName();
            String strCityName = stor.getCityName();
            String strDistName = stor.getDistName();

            //项目环境: normal;sandbox;
            String strEnv = stor.getEnv(); //wangxing add 沙箱环境开发

            reqMap.put("stor_id", strStorId);

            // 获取需要创建的入库单信息
            List<StockInCreate> stockInIdList = stockInCreateService.selectInfoStockInIdByPrjIdAndStorId(reqMap);
            if (stockInIdList == null || stockInIdList.size() <= 0) {
                continue;
            }

            for (StockInCreate stockInId : stockInIdList) {

                String strStockinId = stockInId.getStockinId();// 入库单Id

                reqMap.put("stockin_id", strStockinId);

                StockInCreate StockIn = stockInCreateService.selectInfoStockInByPrjIdAndStorId(reqMap);

                if (StockIn == null) {
                    continue;
                }

                String strStockInCode = StockIn.getEntryOrderCode();// 入库单编号

                // 调用奇门API创建入库单
                // taobao.qimen.entryorder.create
                QimenClient client = new DefaultQimenClient(url, appkey, secret);
                EntryorderCreateRequest req = new EntryorderCreateRequest();
                req.setCustomerId(strQmCustomerid);
                req.setVersion("2.0");

                EntryorderCreateRequest.EntryOrder entryOrder = new EntryorderCreateRequest.EntryOrder();

                entryOrder.setEntryOrderCode(StockIn.getEntryOrderCode());
                entryOrder.setPurchaseOrderCode(StockIn.getPurchaseOrderCode());
                entryOrder.setOwnerCode(strQmOwnercode);
                entryOrder.setWarehouseCode(StockIn.getWarehouseCode());
                entryOrder.setOrderCreateTime(StockIn.getOrderCreateTime());
                entryOrder.setOrderType(StockIn.getOrderType());
                entryOrder.setExpectStartTime(StockIn.getExpectStartTime());
                entryOrder.setExpressCode(StockIn.getExpressCode());
                entryOrder.setLogisticsName(StockIn.getLogisticsName());
                entryOrder.setLogisticsCode(StockIn.getLogisticsCode());
                entryOrder.setSupplierCode(StockIn.getSupplierCode());
                entryOrder.setSupplierName(StockIn.getSupplierName());
                entryOrder.setRemark(StockIn.getRemark());

                EntryorderCreateRequest.SenderInfo senderInfo = new EntryorderCreateRequest.SenderInfo();

                senderInfo.setName(StockIn.getSendername());
                senderInfo.setTel(StockIn.getSendertel());
                senderInfo.setMobile(StockIn.getSendermobile());
                senderInfo.setDetailAddress("senderdetailAddress");
                senderInfo.setProvince("senderprovince");
                senderInfo.setCity("sendercity");
                senderInfo.setArea("senderarea");

                entryOrder.setSenderInfo(senderInfo);

                EntryorderCreateRequest.ReceiverInfo receiverInfo = new EntryorderCreateRequest.ReceiverInfo();

                receiverInfo.setName(StockIn.getrName());
                receiverInfo.setZipCode(strPostCode);
                receiverInfo.setTel(strTel);
                receiverInfo.setMobile(strMobile);
                receiverInfo.setProvince(strProvName);
                receiverInfo.setCity(strCityName);
                receiverInfo.setArea(strDistName);
                receiverInfo.setDetailAddress(strAddr);

                entryOrder.setReceiverInfo(receiverInfo);

                req.setEntryOrder(entryOrder);

                // 入库单商品明细信息接口参数的赋值
                List<EntryorderCreateRequest.OrderLine> orderLines = new ArrayList<EntryorderCreateRequest.OrderLine>();

                Map<String, Object> reqMapSku = new HashMap<String, Object>();
                reqMapSku.put("stockin_id", strStockinId);

                // 获取需要创建的入库单商品信息
                List<StockInSkuCreate> stockInSkuList = stockInCreateService.selectInfoStockInSkuByStockId(reqMapSku);
                if (stockInSkuList == null || stockInSkuList.size() <= 0) {
                    // 插入失败操作日志
                    logUtil.info(new DBLog(strStockInCode, "", "entryOrderCreate", DateUtil.getCurrentDateStr()
                            + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的入库单【" + strStockInCode + "】创建失败, 原因: 没有查询到该入库单的商品信息"));
                    continue;
                }

                for (StockInSkuCreate stockInSku : stockInSkuList) {
                    EntryorderCreateRequest.OrderLine orderLine = new EntryorderCreateRequest.OrderLine();

                    orderLine.setOutBizCode(stockInSku.getOutBizCode());
                    orderLine.setOrderLineNo(stockInSku.getOrderLineNo());// 单据行号
                    orderLine.setOwnerCode(strQmOwnercode);// 货主编码
                    orderLine.setItemCode(stockInSku.getItemCode());// 商品编码
                    orderLine.setItemName(stockInSku.getItemName());
                    orderLine.setItemId(stockInSku.getItemId());// 仓储系统商品编码
                    orderLine.setPlanQty(stockInSku.getPlanQty());// 应收商品数量
                    orderLine.setPurchasePrice(stockInSku.getPurchasePrice());
                    orderLine.setInventoryType(stockInSku.getInventoryType());// 库存类型

                    orderLines.add(orderLine);

                }

                req.setOrderLines(orderLines);

                EntryorderCreateResponse rsp = null;
                //wangxing add 沙箱环境开发
                if ("sandbox".equals(strEnv)) {
                    rsp = new EntryorderCreateResponse();
                    rsp.setBody("沙箱环境");
                    rsp.setEntryOrderId("");
                    rsp.setMessage("沙箱环境");
                } else {
                    //正式环境调用
                    rsp = client.execute(req);
                }

                logUtil.info(new DBLog(strStockInCode, rsp.getBody(), "entryOrderCreate", JSON.toJSONString(req)));

                if ("sandbox".equals(strEnv) || rsp.isSuccess()) {
                    // 仓储系统退货单编码
                    String strEntryOrderId = "";

                    //wangxing add 沙箱环境开发
                    if ("sandbox".equals(strEnv)) {
                        strEntryOrderId = strStockInCode;// 仓储系统退货单编码
                    } else if (rsp.isSuccess()) {
                        strEntryOrderId = rsp.getEntryOrderId();// 仓储系统退货单编码
                    }

                    // strEntryOrderId
                    if (StringUtils.isBlank(strEntryOrderId)) {

                        // 插入失败操作日志
                        logUtil.info(
                                new DBLog(strStockInCode, "", "entryOrderCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                        + strQmCustomerid + "】下的入库单【" + strStockInCode + "】创建失败, 原因: entryOrderId 没有返回值"));
                        continue;
                    }

                    // 更新入库单数据
                    Stockin stockin = new Stockin();
                    stockin.setStockinId(strStockinId);
                    stockin.setWmsStockinCode(strEntryOrderId);
                    stockinService.updateByPrimaryKeySelectiveStockin(stockin);

                    // 插入操作日志
                    logUtil.info(new DBLog(strStockInCode, "", "entryOrderCreate", DateUtil.getCurrentDateStr()
                            + "  奇门自动任务对CUSTOMERID为【" + strQmCustomerid + "】下的入库单【" + strStockInCode + "】创建成功"));

                } else {
                    // 插入失败操作日志
                    logUtil.info(
                            new DBLog(strStockInCode, "", "entryOrderCreate", DateUtil.getCurrentDateStr() + "  奇门自动任务对CUSTOMERID为【"
                                    + strQmCustomerid + "】下的入库单【" + strStockInCode + "】创建失败, 原因: " + rsp.getMessage() + ""));
                }

            }
        }
        return 1;
    }
}
